package com.cyclingAssistant.util;

import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.osmdroid.util.GeoPoint;

import android.util.Log;

public class Geocoder {
	
	public static GeoPoint geocoding(String locatoin) {
		return getGeoPoint(getLocationInfo(locatoin));
	}

	public static String getFormattedAddress(String locatoin) {
		try {
			return ((JSONArray) getLocationInfo(locatoin).get("results")).getJSONObject(0)
					.getString("formatted_address");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
	}
	
	public static String getFormattedAddress(double lat, double lon) {
		try {
			return ((JSONArray) getLocationInfo(lat, lon).get("results")).getJSONObject(0)
					.getString("formatted_address");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
	}
	
	private static GeoPoint getGeoPoint(JSONObject jsonObject) {

		Double lon = new Double(0);
		Double lat = new Double(0);

		try {

			lon = ((JSONArray) jsonObject.get("results")).getJSONObject(0)
					.getJSONObject("geometry").getJSONObject("location")
					.getDouble("lng");

			lat = ((JSONArray) jsonObject.get("results")).getJSONObject(0)
					.getJSONObject("geometry").getJSONObject("location")
					.getDouble("lat");

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return new GeoPoint((int) (lat * 1E6), (int) (lon * 1E6));

	}

	private static JSONObject getLocationInfo(double lat, double lon) {
		// String[] addressSplit = address.trim().split(",");
		// StringBuilder addressBuilder = new StringBuilder();
		// addressBuilder.append("http://maps.google.com/maps/api/geocode/json?address=")
		
		HttpGet httpGet = new HttpGet("http://maps.google."
				+ "com/maps/api/geocode/json?latlng=" + String.valueOf(lat)+"," +String.valueOf(lon)  
				+ "&sensor=false");
		HttpClient client = new DefaultHttpClient();
		HttpResponse response;
		StringBuilder stringBuilder = new StringBuilder();

		try {
			response = client.execute(httpGet);
			HttpEntity entity = response.getEntity();
			InputStream stream = entity.getContent();
			int b;
			while ((b = stream.read()) != -1) {
				stringBuilder.append((char) b);
			}
		} catch (ClientProtocolException e) {
		} catch (IOException e) {
		}

		JSONObject jsonObject = new JSONObject();
		try {
			jsonObject = new JSONObject(stringBuilder.toString());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return jsonObject;
	}
	
	private static JSONObject getLocationInfo(String address) {
		// String[] addressSplit = address.trim().split(",");
		// StringBuilder addressBuilder = new StringBuilder();
		// addressBuilder.append("http://maps.google.com/maps/api/geocode/json?address=")
		Log.v("HttpGet", address);
		HttpGet httpGet = new HttpGet("http://maps.google."
				+ "com/maps/api/geocode/json?address=" + address.replace(",", "+").replace(" ", "+") + "+Vancouver"
				+ "&sensor=false");
		HttpClient client = new DefaultHttpClient();
		HttpResponse response;
		StringBuilder stringBuilder = new StringBuilder();

		try {
			response = client.execute(httpGet);
			HttpEntity entity = response.getEntity();
			InputStream stream = entity.getContent();
			int b;
			while ((b = stream.read()) != -1) {
				stringBuilder.append((char) b);
			}
		} catch (ClientProtocolException e) {
		} catch (IOException e) {
		}

		JSONObject jsonObject = new JSONObject();
		try {
			jsonObject = new JSONObject(stringBuilder.toString());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return jsonObject;
	}
}
//
//{
//	  "status": "OK",
//	  "results": [ {
//	    "types": [ "street_address" ],
//	    "formatted_address": "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
//	    "address_components": [ {
//	      "long_name": "1600",
//	      "short_name": "1600",
//	      "types": [ "street_number" ]
//	    }, {
//	      "long_name": "Amphitheatre Pkwy",
//	      "short_name": "Amphitheatre Pkwy",
//	      "types": [ "route" ]
//	    }, {
//	      "long_name": "Mountain View",
//	      "short_name": "Mountain View",
//	      "types": [ "locality", "political" ]
//	    }, {
//	      "long_name": "California",
//	      "short_name": "CA",
//	      "types": [ "administrative_area_level_1", "political" ]
//	    }, {
//	      "long_name": "United States",
//	      "short_name": "US",
//	      "types": [ "country", "political" ]
//	    }, {
//	      "long_name": "94043",
//	      "short_name": "94043",
//	      "types": [ "postal_code" ]
//	    } ],
//	    "geometry": {
//	      "location": {
//	        "lat": 37.4219720,
//	        "lng": -122.0841430
//	      },
//	      "location_type": "ROOFTOP",
//	      "viewport": {
//	        "southwest": {
//	          "lat": 37.4188244,
//	          "lng": -122.0872906
//	        },
//	        "northeast": {
//	          "lat": 37.4251196,
//	          "lng": -122.0809954
//	        }
//	      }
//	    }
//	  } ]
//	}
